package com.cqvip.innocence.framework.security;

import com.cqvip.innocence.common.exception.ServiceException;
import com.cqvip.innocence.framework.jwt.dto.LoginAdmin;
import com.cqvip.innocence.project.model.dto.JsonResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName SecurityUtils
 * @Description: 安全工具类
 * @Author Innocence
 * @Date 2022/5/26 14:54
 * @Version 1.0
 */
public class SecurityUtils {

    /**
     * 获取管理员用户
     *
     * @return com.cqvip.innocence.framework.jwt.dto.LoginAdmin
     * @author Innocence
     * @date 2022/5/26
     */
    public static LoginAdmin getLoginAdmin() {
        try {
            return (LoginAdmin) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", JsonResult.UNAUTHORIZED);
        }
    }

    /**
     * 获取Authentication
     *
     * @return org.springframework.security.core.Authentication
     * @author Innocence
     * @date 2022/5/26
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     * @author Innocence
     * @date 2022/5/26
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     * @author Innocence
     * @date 2022/5/26
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

}
